//  聊天气泡
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/models/contact_model.dart';
import 'package:chat_client/models/conversation_model.dart';
import 'package:chat_client/models/user_model.dart';
import 'package:chat_client/repositories/contact_repository.dart';
import 'package:chat_client/services/user_service.dart';
import 'package:chat_client/widgets/c_square_avatar.dart';
import 'package:flutter/material.dart';

class ChatBubble extends StatefulWidget {
  final Message message;
  final String userId;
  final bool isGroup;

  const ChatBubble({
    super.key,
    required this.message,
    required this.userId,
    required this.isGroup,
  });

  @override
  ChatBubbleState createState() => ChatBubbleState();
}

class ChatBubbleState extends State<ChatBubble> {
  final UserService _userService = UserService.instance;
  final ContactRepository _contactRepository = ContactRepository.instance;

  // 是否为系统时间信息
  bool _isMe = false;
  // 是否为我方发送
  bool _isTime = false;

  String _avatarUrl = '';
  String? _nickname;

  @override
  void initState() {
    _init();
    super.initState();
  }

  _init() {
    // 1. 判断是否为系统时间信息
    _isTime = widget.message.senderId == null;
    if (_isTime) return;
    // 2. 判断是否为我方发送的消息
    _isMe = widget.message.senderId == widget.userId;

    // 如果为 我方发送则使用本地信息加载
    if (_isMe) {
      final User user = _userService.getLocalUserInfo();
      _avatarUrl = AppConfig.baseUrl + user.avatarUrl;
      _nickname = user.nickname;
    }
    // 如果是单聊，对方发送的消息
    else if (!widget.isGroup) {
      return;
    }
    // 群聊
    final Contact? contact =
        _contactRepository.getContact(widget.message.senderId!);
    if (contact != null) {
      _nickname = contact.nickname;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: _isMe ? Alignment.centerRight : Alignment.centerLeft,
      child: _isTime ? _buildTimeTip() : _buildBubble(),
    );
  }

  // 气泡
  Widget _buildBubble() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      child: Row(
          mainAxisAlignment:
              _isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (!_isMe) ..._buildLeftBubble(),
            if (_isMe) ..._buildRightBubble(),
          ]),
    );
  }

  // 构建对方消息
  List<Widget> _buildLeftBubble() {
    return [
      SquareAvatar(
        size: 56,
        imageSource: AppConfig.baseUrl + widget.message.senderAvatar!,
      ),
      SizedBox(width: 6),
      CustomPaint(
        painter: TrianglePainter(
          color: Colors.white,
          direction: TriangleDirection.left,
          yOffset: widget.isGroup ? 30.0 : 18,
        ),
        size: Size(20, 20), // 容器不小于固定尺寸
      ),
      Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        if (widget.isGroup)
          Text(_nickname ?? widget.message.senderNickname!,
              style: TextStyle(fontSize: 12)),
        SizedBox(height: 4),
        _buildTextBubble()
      ]),
    ];
  }

  // 构建我发消息
  List<Widget> _buildRightBubble() {
    return [
      Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
        if (widget.isGroup)
          Text(_nickname ?? '', style: TextStyle(fontSize: 12)),
        SizedBox(height: 4),
        _buildTextBubble()
      ]),
      CustomPaint(
        painter: TrianglePainter(
          color: Color(0xFF99A8F1),
          direction: TriangleDirection.right,
          yOffset: widget.isGroup ? 30.0 : 18,
        ),
        size: Size(20, 20), // 容器不小于固定尺寸
      ),
      SizedBox(width: 6),
      SquareAvatar(size: 56, imageSource: _avatarUrl),
    ];
  }

  // 文字气泡
  Widget _buildTextBubble() {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.6,
      ),
      padding: EdgeInsets.symmetric(vertical: 14, horizontal: 14),
      decoration: BoxDecoration(
        color: _isMe ? Color(0xFF99A8F1) : Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(widget.message.data, overflow: TextOverflow.visible),
    );
  }

  // 系统时间信息
  Widget _buildTimeTip() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 40, horizontal: 8),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [Text(widget.message.data)]),
    );
  }
}

class TrianglePainter extends CustomPainter {
  static const double _fixedSize = 20.0; // 固定三角形尺寸
  final Color color; // 三角形颜色
  final TriangleDirection direction; // 方向控制
  final double yOffset; // Y 轴偏移量

  TrianglePainter({
    this.color = const Color(0xFF4C4C4C),
    this.direction = TriangleDirection.right,
    this.yOffset = 20.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    // 应用 Y 轴偏移（保持 X 轴居中）
    canvas.translate(
      (size.width - _fixedSize) / 2, // 水平居中
      yOffset,
    );

    canvas.drawPath(_buildTrianglePath(), paint);
  }

  Path _buildTrianglePath() {
    final path = Path();

    // 基于固定尺寸构建路径
    switch (direction) {
      case TriangleDirection.right:
        path
          ..moveTo(_fixedSize / 3 * 2, _fixedSize / 2)
          ..lineTo(0, 0)
          ..lineTo(0, _fixedSize);
        break;
      case TriangleDirection.left:
        path
          ..moveTo(0, _fixedSize / 2)
          ..lineTo(_fixedSize, 0)
          ..lineTo(_fixedSize, _fixedSize);
        break;
    }

    return path..close();
  }

  @override
  bool shouldRepaint(covariant TrianglePainter old) {
    return old.color != color ||
        old.direction != direction ||
        old.yOffset != yOffset;
  }
}

enum TriangleDirection {
  right,
  left,
}
